﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using TheGameClient.Processes;
using TheGameClient.Webservices;
using Waaahsabi.Controls.TheGame;

namespace TheGameClient.SoftwareUI.FeatureUI
{
	public partial class FeatureLogViewerControl : ISystemFeature
	{
		private ObservableCollection<GenericLogItem> _logItems;

		public FeatureLogViewerControl()
		{
			InitializeComponent();
			ProcessId = Guid.NewGuid();
			_logItems = new ObservableCollection<GenericLogItem>();
			itmLogItems.ItemsSource = _logItems;
			HorizontalAlignment = HorizontalAlignment.Stretch;
			VerticalAlignment = VerticalAlignment.Stretch;
		}

		public ObservableCollection<GenericLogItem> LogItems
		{
			get
			{
				if (_logItems == null)
					_logItems = new ObservableCollection<GenericLogItem>();
				return _logItems;
			}
		}

		#region ISystemFeature Members

		public ulong InterfaceId
		{
			get { return new Guid("{4EF4C236-230B-4ad2-8CA2-7CFF89093010}").ToLong(); }
		}

		public Guid ProcessId { get; private set; }

		public string ProcessName
		{
			get { return "Log Viewer"; }
		}

		public InterfaceCategory Category
		{
			get { return InterfaceCategory.SystemFeature; }
		}

		public ulong SystemId { get; private set; }

		public void Load(ulong systemId)
		{
			SystemId = systemId;
			TheGameServiceClient client = App.Client;
			client.GetSystemLogsCompleted += (s, e) =>
			{
				if (e.Result != null)
				{
					_logItems.Clear();
					(from log in e.Result
					 select new GenericLogItem
					 {
					 	LogAction = log.Activity,
					 	LogAffectedItem = log.ModifiedItem,
					 	LogSourceIP = log.ConnectingSystemAddress,
					 	LogTimestamp = log.TimeStamp == new DateTime() ? "--" : log.TimeStamp.ToString("yyyy/MM/dd HH:mm"),
					 	LogId = log.Id,
					 	Opacity = log.Activity == "--" ? 0.5 : 1.0
					 }
					).ToList().ForEach(it => _logItems.Add(it));
					//foreach (ReadableComputerSystemLog log in _e.Result)
					//{
					//    GenericLogItem item = new GenericLogItem
					//    {
					//        LogAction = log.Activity,
					//        LogAffectedItem = log.ModifiedItem,
					//        LogSourceIP = log.ConnectingSystemAddress,
					//        LogTimestamp = log.TimeStamp == new DateTime() ? "--" : log.TimeStamp.ToString("YYYY/MM/dd HH:mm"),
					//        LogId = log.ID
					//    };
					//    logItems.Add(item);
					//}
				}
			};
			client.GetSystemLogsAsync(App.InternalSessionId, SystemId);
		}

		#endregion
	}

	public class FeatureLogViewerUiFactory : UiFactoryBase
	{
		public override InterfaceCategory UiCategory
		{
			get { return InterfaceCategory.SystemFeature; }
		}

		public override IProcess CreateProgram()
		{
			return new FeatureLogViewerControl();
		}
	}
}